package com.example.statistics.ui.purchase

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import com.example.statistics.R
import com.example.statistics.bean.*
import com.example.statistics.common.BaseActivity
import com.example.statistics.common.FileDisplayActivity
import com.example.statistics.common.MultiSelectListActivity
import com.example.statistics.ex.*
import com.example.statistics.net.UrlConfig
import com.example.statistics.net.callback.UploadDialogHttpCallback
import com.example.statistics.utils.Constants
import com.example.statistics.utils.activityForResult
import com.jhj.httplibrary.HttpCall
import com.jhj.slimadapter.SlimAdapter
import com.example.statistics.ex.afterTextChangedListener
import com.example.statistics.ex.contentText
import com.example.statistics.ex.glide
import com.example.statistics.ex.onSingleLongClicked
import kotlinx.android.synthetic.main.activity_purchase_futures_product.*
import kotlinx.android.synthetic.main.layout_purchase_type_title.view.*
import kotlinx.android.synthetic.main.table_row_futures_fee.view.*
import kotlinx.android.synthetic.main.table_row_futures_fee.view.tv_date
import kotlinx.android.synthetic.main.table_row_futures_fee.view.tv_type
import kotlinx.android.synthetic.main.table_row_settlement.view.*
import kotlinx.android.synthetic.main.table_row_storage_fee.view.*
import org.jetbrains.anko.find
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.jetbrains.anko.sdk27.coroutines.onLongClick
import org.jetbrains.anko.startActivity
import java.io.File
import java.math.BigDecimal
import java.util.Date

/**
 * 新增期货采购
 */

@Deprecated(message = "")
class PurchaseProductActivity : BaseActivity() {

    private var purchaseId = -1
    private var containerNo = ""
    private var purchaseProductBean: PurchaseProductBean? = null
    private val futuresFeeList = listOf("预付定金", "实际定金", "预估定金", "预付保证金", "实际保证金", "预付尾款", "实际尾款", "预估尾款")
    private val futuresFeeArray = mutableMapOf<String, FuturesFeeBean>()

    private var clearanceAdapter: SlimAdapter? = null
    private var certificateAdapter: SlimAdapter? = null
    private var billAdapter: SlimAdapter? = null

    private var productValuationWeight = 0.0 //计价重量

    override val title: String
        get() = intent.getStringExtra(Constants.TITLE) ?: "采购"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_purchase_futures_product)
        purchaseId = intent.getIntExtra(Constants.PURCHASE_PRODUCT_ID, -1)
        initView()
    }

    @SuppressLint("SetTextI18n")
    private fun initData() {
        httpGet<PurchaseProductBean>(UrlConfig.PURCHASE_PRODUCT_DATA, config = {
            listParams = listOf("id" to purchaseId)
        }) { data ->
            if (data != null) {
                purchaseProductBean = data
                purchaseId = data.ID
                containerNo = purchaseProductBean?.containerNo.orEmpty()
                certificateAdapter?.setDataList(data.fileList?.filter { it.type == "certificate" }.orEmpty())
                billAdapter?.setDataList(data.fileList?.filter { it.type == "bill" }.orEmpty())
                productValuationWeight = if (data.weightUnit == "磅") {
                    if (data.productNumber < 1300) {
                        data.productNumber * 20.toDouble()
                    } else {
                        data.productNumber * 13.607679
                    }
                } else {
                    data.productWeight
                }


                data.futuresFeeList?.forEach {
                    futuresFeeArray[it.feeType] = it
                }
                futuresFee()
                val portInfo = data.shippingInfo
                if (portInfo?.deliveryDate.goTimeFormat() != null) refreshFee()
                if (data.taxFee != null) taxFee()

                if (data.financingFeeList != null) {
                    financingFee()
                }
                if (data.storageFeeList != null) {
                    storageFee()
                }
                if (!data.settlementFeeList.isNullOrEmpty()) {
                    settlement()
                }
                if (!data.clearanceFeeList.isNullOrEmpty()) {
                    recycler_view_clearance.visibility = View.VISIBLE
                    clearanceAdapter?.setDataList(data.clearanceFeeList.orEmpty())
                    data.clearanceFeeList?.sumEx { it.value }.let {
                        tv_clearance_fee.contentText = it.toString()
                        layout_clearance.tv_fee.text = "($it)"
                    }
                } else {
                    recycler_view_clearance.visibility = View.GONE
                }

                tv_container_no.text = "集装箱号：${data.containerNo}"
                tv_contract_no.text = "合同编号：${data.contractNo}"
                tv_product_price.text = "商品单价：${data.priceUnit}${data.productPrice}"
                tv_product_weight.text = "商品重量：${data.productWeight}${data.weightUnit}"
                tv_product_number.text = "商品件数：${data.productNumber}件"
                tv_total_price.text = "商品总价：${data.priceUnit}${data.productTotalPrice}"
                tv_remark.text = data.remark
                tv_remark.visibility = if (!data.remark.isNullOrBlank()) View.VISIBLE else View.GONE


                tv_arrival_time.contentText = portInfo?.arrivalDate.goTimeFormat()
                tv_port_position.contentText = portInfo?.port
                tv_warehousing_time.contentText = portInfo?.warehousingDate.goTimeFormat()
                tv_cold_storage.contentText = portInfo?.coldStorage.toString()
                tv_delivery_time.contentText = portInfo?.deliveryDate.goTimeFormat()
                tv_flow_city.contentText = data.salesCustomer ?: data.flowCity.orEmpty()
                tv_sales_price.contentText = data.salesPrice.toString()
            }
        }
    }

    private fun refreshFee() {
        if (purchaseProductBean?.shippingInfo?.deliveryDate.goTimeFormat().isNullOrBlank()) {
            layout_fee.visibility = View.GONE
        } else {
            val futuresFee =
                futuresFeeArray["实际定金"]?.totalFee.addEx(futuresFeeArray["实际尾款"]?.totalFee)
                    .addEx(futuresFeeArray["实际保证金"]?.totalFee)

            val taxFee = purchaseProductBean?.taxFee?.tariff.addEx(purchaseProductBean?.taxFee?.valueAddedTax)
                .addEx(purchaseProductBean?.taxFee?.taxDifference)

            val financingFee = purchaseProductBean?.financingFeeList?.sumEx {
                it.financingInterest ?: 0.0
            }
            val clearanceFee = purchaseProductBean?.clearanceFeeList?.sumEx { it.value }

            val storageFee = purchaseProductBean?.storageFeeList?.sumEx { it.storageFee }
            //费用清单费用
            val fee = futuresFee.addEx(taxFee).addEx(financingFee).addEx(clearanceFee).addEx(storageFee)
            //付款结算费用
            val settlementFee = purchaseProductBean?.settlementFeeList?.sumEx { it.amount }
            val difference = fee.subEx(settlementFee)
            val status = if (difference.toDouble() > 0) "欠" else if (difference.toDouble() == 0.0) "" else "多"
            tv_difference_fee.contentText = "${status}$difference"
            layout_fee.visibility = View.VISIBLE

            //利润
            val profit = purchaseProductBean?.salesPrice.mulEx(productValuationWeight.divEx(10)).subEx(fee).toString()
            tv_profit.contentText = profit

            portUpdate("profit" to profit, "feeDifference" to difference.toString())
        }
    }


    private fun initView() {
        initData()
        layout_payment.tv_title.text = "货款"
        layout_tax.tv_title.text = "税款"
        layout_clearance.tv_title.text = "清关"
        layout_financing.tv_title.text = "融资"
        layout_storage.tv_title.text = "仓储"
        layout_settlement.tv_title.text = "付款单"
        layout_files.tv_title.text = "手续"
        layout_fee_files.tv_title.text = "结算单"
        recycler_view_clearance.layoutManager = GridLayoutManager(this@PurchaseProductActivity, 2)
        clearanceAdapter = SlimAdapter.creator()
            .register<ClearanceBean>(R.layout.list_item_clearance_fee_display) { injector, bean, _ ->
                injector.text(R.id.tv_key, "${bean.name}：").text(R.id.tv_value, bean.value.toString())
            }.attachTo(recycler_view_clearance)

        certificateAdapter = fileAdapter("certificate").attachTo(recycler_view_file)
        billAdapter = fileAdapter("bill").attachTo(recycler_view_fee)

        layout_info_display.onClick {
            activityForResult<PurchaseProductEditActivity>(Constants.DATA to purchaseProductBean) {
                initData()
            }
        }

        tv_port_position.onContentClicked {
            bottomSingleDialog(list = listOf("上海", "天津", "盐田")) { _, s ->
                tv_port_position.contentText = s
                portUpdate("port" to s)
            }
        }
        tv_arrival_time.onDateClicked {
            tv_arrival_time.contentText = it
            portUpdate("arrivalTime" to it)
        }
        tv_warehousing_time.onDateClicked {
            tv_warehousing_time.contentText = it
            portUpdate("warehousingTime" to it)
        }
        tv_delivery_time.onDateClicked {
            tv_delivery_time.contentText = it
            portUpdate("deliveryTime" to it)
            refreshFee()
        }
        tv_cold_storage.onClick {
            httpGet<List<ColdStorageBean>>(UrlConfig.PURCHASE_STORAGE_LIST, config = {
                listParams = listOf("city" to tv_port_position.contentText)
            }) {
                singleDialog(it) { storage ->
                    tv_cold_storage.contentText = storage.storage
                    portUpdate("coldStorage" to storage.storage)
                }
            }
        }

        tv_flow_city.afterTextChangedListener { editable, _ ->
            portUpdate("salesCustomer" to editable.toString())
        }
        tv_sales_price.afterTextChangedListener { editable, _ ->
            portUpdate("salesPrice" to editable.toString())
        }
        layout_payment.iv_add.onClick {
            futures()
        }


        layout_clearance.iv_add.onClick {
            //有清关费用进入清关费用详情，无清关费用进入清关item列表
            if (!purchaseProductBean?.clearanceFeeList.isNullOrEmpty()) {
                clearanceFee()
            } else {
                activityForResult<MultiSelectListActivity>(
                    Constants.TITLE to title,
                    Constants.TYPE to ClearanceBean::class.java,
                    Constants.PATH to UrlConfig.PURCHASE_CLEARANCE_FIELD_LIST,
                    Constants.DATA to purchaseProductBean?.clearanceFeeList?.map { it.id }) { intent ->
                    purchaseProductBean?.clearanceFeeList =
                        (intent?.getSerializableExtra(Constants.DATA) as? List<ClearanceBean>).orEmpty()
                    clearanceFee()
                }
            }
        }
        layout_tax.iv_add.onClick {
            val totalPrice = purchaseProductBean?.productTotalPrice ?: 0.0
            activityForResult<TaxFeeActivity>(
                Constants.TITLE to title,
                Constants.AMOUNT to totalPrice,
                Constants.DATA to purchaseProductBean?.taxFee,
                Constants.CONTAINER_NO to containerNo,
                Constants.TYPE to purchaseProductBean?.priceUnit
            ) {
                layout_tax.iv_add.visibility = View.GONE
                taxFee()
            }
        }
        layout_tax_fee.onLongClick {
            bottomSingleDialog(list = listOf("编辑", "删除")) { _, s ->
                if (s == "编辑") {
                    activityForResult<TaxFeeActivity>(
                        Constants.TITLE to title,
                        Constants.DATA to purchaseProductBean?.taxFee,
                        Constants.CONTAINER_NO to containerNo,
                        Constants.TYPE to purchaseProductBean?.priceUnit
                    ) {
                        taxFee()
                    }
                } else {
                    messageDialog(msg = "是否删除税款？") { _, _ ->
                        httpGet<Any>(UrlConfig.PURCHASE_TAX_DELETE, config = {
                            listParams = listOf("id" to purchaseProductBean?.taxFee?.ID)
                        }) {
                            taxFee()
                        }
                    }
                }
            }
        }



        layout_financing.iv_add.onClick {
            bottomSingleDialog(list = listOf("定金", "尾款", "税款")) { _, s ->
                val endDate = purchaseProductBean?.shippingInfo?.deliveryDate
                    ?: Date().format().orEmpty()
                if (s == "尾款") {
                    activityForResult<FinancingFeeEditActivity>(
                        Constants.TYPE to s, Constants.AGENT_ID to purchaseProductBean?.agentId,//代理id，
                        Constants.PURCHASE_PRODUCT_ID to purchaseId,
                        Constants.CONTAINER_NO to containerNo,//采购商品的id
                        Constants.DATA to purchaseProductBean?.futuresFeeList, //货款
                        Constants.DATE to endDate
                    ) {
                        financingFee()
                    }
                } else if (s == "税款") {
                    activityForResult<FinancingFeeEditActivity>(
                        Constants.TYPE to s, Constants.AGENT_ID to purchaseProductBean?.agentId,//代理id
                        Constants.PURCHASE_PRODUCT_ID to purchaseId,
                        Constants.CONTAINER_NO to containerNo,//采购商品的id
                        Constants.DATA to purchaseProductBean?.taxFee,//税款
                        Constants.DATE to endDate
                    ) {
                        financingFee()
                    }
                }
            }
        }
        layout_storage.iv_add.onClick {
            val portInfo = purchaseProductBean?.shippingInfo
            activityForResult<StorageFeeEditActivity>(
                Constants.STORAGE to tv_cold_storage.contentText,
                Constants.START_DATE to portInfo?.warehousingDate,
                Constants.PURCHASE_PRODUCT_ID to purchaseId,
                Constants.END_DATE to portInfo?.deliveryDate,
                Constants.CONTAINER_NO to containerNo,
                Constants.WEIGHT to productValuationWeight,
                Constants.CITY to portInfo?.port
            ) {
                storageFee()
            }
        }
        layout_settlement.iv_add.onClick {
            activityForResult<SettlementFeeEditActivity>(Constants.PURCHASE_PRODUCT_ID to purchaseId) {
                settlement()
            }
        }
        layout_files.iv_add.onClick {
            fillSelector("certificate")
        }
        layout_fee_files.iv_add.onClick {
            fillSelector("bill")
        }
    }

    private fun fillSelector(type: String) {
        bottomSingleDialog(list = listOf("文件", "图片")) { _, s ->
            if (s == "文件") {
                fileSelected {
                    addFiles(type, listOf(File(it.path.orEmpty())))
                }
            } else {
                imageSelected { list ->
                    addFiles(type, list.map { File(it.compressPath) })
                }
            }
        }
    }

    private fun fileAdapter(type: String): SlimAdapter {
        return slimAdapter<FilesBean>(R.layout.list_item_document) { bean ->
            val create = bean.size.fileSize + " | " + bean.createTime.goTimeFormat("yyyy-MM-dd HH:mm:ss")
            glide(R.id.iv_file_icon, bean.path.fileTypeIcon)
            text(R.id.tv_file_title, bean.name)
            text(R.id.tv_file_create, create)
            gone(R.id.iv_file_more)
            onSingleLongClicked("重命名", "删除") { s ->
                if (s == "重命名") {

                } else {
                    messageDialog(msg = "是否删除${bean.name}?") { _, _ ->
                        httpGet<Any>(UrlConfig.PURCHASE_FILE_DELETE, config = {
                            listParams = listOf("id" to bean.id)
                        }) {
                            refreshFileAdapter(type)
                        }
                    }
                }
            }
            clicked {
                if (bean.suffix == ".jpg" || bean.suffix == ".png") {
                    imageDisplay(listOf(HttpCall.baseUrl + bean.path))
                } else {
                    startActivity<FileDisplayActivity>(Constants.DATA to bean)
                }
            }
        }
    }

    private fun refreshFileAdapter(type: String = "certificate") {
        httpGet<List<FilesBean>>(UrlConfig.PURCHASE_FILE_LIST, config = {
            listParams = listOf("identification" to purchaseId, "type" to type)
        }) {
            if (type == "certificate") {
                certificateAdapter?.setDataList(it.orEmpty())
            } else {
                billAdapter?.setDataList(it.orEmpty())
            }
        }
    }

    private fun addFiles(type: String, filesList: List<File>) {
        val folder = if (purchaseProductBean?.contractNo.isNullOrBlank())
            purchaseProductBean?.agent
        else
            purchaseProductBean?.contractNo
        HttpCall.post(UrlConfig.PURCHASE_FILE_SAVE)
            .addFiles("files[]", filesList)
            .addParam("type", type)
            .addParam("identification", purchaseId)//标识
            .addParam("folder", folder)//分块
            .enqueue(object : UploadDialogHttpCallback<List<FilesBean>>(this) {
                override fun onSuccess(data: List<FilesBean>?, resultType: ResultType) {
                    refreshFileAdapter(type)
                }
            })
    }

    private fun portUpdate(vararg pair: Pair<String, Any>) {
        val list = mutableListOf<Pair<String, Any>>()
        pair.forEach {
            list.add(it.first to it.second)
        }
        list.add("id" to purchaseId)
        httpPost<PurchaseProductBean>(UrlConfig.PURCHASE_PRODUCT_MODIFY, config = {
            listParams = list
        })
    }

    /**
     * 货款
     */
    private fun futures() {
        if (purchaseProductBean != null) {
            val feeTypeList = purchaseProductBean?.futuresFeeList?.map { it.feeType }
            val resultList = futuresFeeList.filter { feeTypeList != null && !feeTypeList.contains(it) }

            bottomSingleDialog(list = resultList) { _, s ->
                val totalPrice = purchaseProductBean?.productTotalPrice ?: 0.0
                val amount = when (s) {
                    "预付定金" -> totalPrice.mulEx(0.3, 2)
                    "实际定金", "预估定金" -> BigDecimal(futuresFeeArray["预付定金"]?.dollar ?: 0.0)
                    "预付保证金", "实际保证金" -> totalPrice.mulEx(0.3, 2).subEx(futuresFeeArray["预付定金"]?.dollar)
                    "预付尾款", "实际尾款" -> totalPrice.subEx(futuresFeeArray["预付定金"]?.dollar)
                        .subEx(futuresFeeArray["预付保证金"]?.dollar)
                    "预估尾款" -> totalPrice.subEx(futuresFeeArray["预付定金"]?.dollar)
                    else -> BigDecimal(0)
                }

                activityForResult<FuturesFeeActivity>(
                    Constants.TITLE to s,
                    Constants.AMOUNT to amount.toDouble(),
                    Constants.PURCHASE_PRODUCT_ID to purchaseId
                ) {
                    futuresFee()
                }
            }
        }
    }

    /**
     * 货款
     */
    private fun futuresFee() {
        httpGet<List<FuturesFeeBean>>(UrlConfig.PURCHASE_FUTURES_LIST, config = {
            listParams = listOf("purchaseProductId" to purchaseId)
        }) { data ->
            purchaseProductBean?.futuresFeeList = data
            futuresFeeArray.clear()
            data?.forEach {
                futuresFeeArray[it.feeType] = it
            }
            refreshFee()
            if (data.isNullOrEmpty()) {
                layout_futures.visibility = View.GONE
                return@httpGet
            }
            layout_futures.visibility = View.VISIBLE
            table_layout.removeAllViews()
            table_layout.addView(inflater.inflate(R.layout.table_row_futures_fee_field, table_layout, false))
            futuresFeeList.forEach { type ->
                data.find {
                    (it.feeType == type) && (type.contains("定金") || type.contains("尾款") || type.contains("保证金"))
                }?.let {
                    val view = inflater.inflate(R.layout.table_row_futures_fee, table_layout, false)
                    view.tv_type.text = it.feeType
                    view.tv_date.text = it.date.goTimeFormat()
                    view.tv_dollar.text = it.dollar.toString()
                    view.tv_rate.text = it.exchangeRate.toString()
                    view.tv_rmb.text = it.rmb.toString()
                    view.tv_handling_fee.text = it.handlingFee.toString()
                    view.tv_wire_transfer_fee.text = it.wireTransferFee.toString()
                    view.tv_total_fee.text = it.totalFee.toString()
                    view.onSingleLongClicked("编辑", "删除") { s ->
                        if (s == "编辑") {
                            activityForResult<FuturesFeeActivity>(Constants.TITLE to it.feeType, Constants.DATA to it) {
                                futuresFee()
                            }
                        } else {
                            httpGet<Any>(UrlConfig.FUTURES_FEE_DELETE, config = {
                                listParams = listOf("id" to it.ID)
                            }) {
                                futuresFee()
                            }
                        }
                    }
                    table_layout.addView(view)
                }
            }

            val deposit = futuresFeeArray["实际定金"]
            val balance = futuresFeeArray["实际尾款"]
            val bail = futuresFeeArray["实际保证金"]
            val total = deposit?.totalFee.addEx(balance?.totalFee).addEx(bail?.totalFee).toDouble()
            val futuresFee = deposit?.rmb.addEx(balance?.rmb).addEx(bail?.rmb)
            val serviceCharge =
                deposit?.handlingFee.addEx(deposit?.wireTransferFee)
                    .addEx(balance?.handlingFee.addEx(balance?.wireTransferFee))
                    .addEx(bail?.handlingFee.addEx(bail?.wireTransferFee))

            val price = "$futuresFee + $serviceCharge = $total"
            layout_payment.tv_fee.text = if (total != 0.0) "($price)" else ""
            tv_futures_fee.contentText = if (total != 0.0) total.toString() else ""

            if (purchaseProductBean?.agentId == 2) { //手续费放在清关费用中
                val depositDifference = futuresFeeArray["预付定金"]?.rmb.subEx(futuresFeeArray["实际定金"]?.rmb).toDouble()
                val depositText = if (depositDifference > 0) "多" else "欠"
                tv_deposit_difference.contentText = "定金差额：${depositText}${depositDifference}"

                val marginDifference = futuresFeeArray["预付保证金"]?.rmb.subEx(futuresFeeArray["实际保证金"]?.rmb).toDouble()
                val marginText = if (marginDifference > 0) "多" else "欠"
                tv_margin_difference.contentText = "保证金差额：${marginText}${marginDifference}"
            } else {
                val depositDifference =
                    futuresFeeArray["预付定金"]?.totalFee.subEx(futuresFeeArray["实际定金"]?.totalFee).toDouble()
                val depositText = if (depositDifference > 0) "多" else "欠"
                tv_deposit_difference.contentText = "定金差额：${depositText}${depositDifference}"

                val marginDifference =
                    futuresFeeArray["预付保证金"]?.totalFee.subEx(futuresFeeArray["实际保证金"]?.totalFee).toDouble()
                val marginText = if (marginDifference > 0) "多" else "欠"
                tv_margin_difference.contentText = "保证金差额：${marginText}${marginDifference}"
            }
        }
    }


    /**
     * 税款
     */
    private fun taxFee() {
        httpGet<TaxFeeBean>(UrlConfig.PURCHASE_TAX_DATA, config = {
            listParams = listOf("containerNo" to containerNo)
        }, result = { taxFeeBean ->
            purchaseProductBean?.taxFee = taxFeeBean
            refreshFee()
            if (taxFeeBean != null) {
                layout_tax_fee.visibility = View.VISIBLE
                layout_tax.iv_add.visibility = View.GONE
                tv_tax_day.text = taxFeeBean.date.goTimeFormat()
                tv_tax_rate.text = taxFeeBean.rate.toString()
                tv_tariff_fee.text = taxFeeBean.tariff.toString()
                tv_value_added_tax_fee.text = taxFeeBean.valueAddedTax.toString()
                tv_tax_difference_fee.text = taxFeeBean.taxDifference.toString()
                tr_rax_different.visibility = if (taxFeeBean.taxDifference != 0.0) View.VISIBLE else View.GONE
                val text =
                    "${taxFeeBean.tariff.addEx(taxFeeBean.valueAddedTax)} + ${taxFeeBean.taxDifference} = ${taxFeeBean.totalFee}"
                layout_tax.tv_fee.contentText = ("($text)")
                tv_tax_fee.contentText = taxFeeBean.totalFee.toString()
            } else {
                layout_tax.tv_fee.text = ""
                layout_tax_fee.visibility = View.GONE
                layout_tax.iv_add.visibility = View.VISIBLE
            }
        })
    }

    private fun storageFee() {
        httpGet<List<StorageBean>>(UrlConfig.PURCHASE_STORAGE_FEE_LIST, config = {
            listParams = listOf("containerNo" to containerNo)
        }) {
            purchaseProductBean?.storageFeeList = it
            refreshFee()
            table_layout_storage.removeAllViews()
            table_layout_storage.visibility = View.VISIBLE
            val fieldView = inflater.inflate(R.layout.table_row_storage_fee_field, table_layout_storage, false)
            table_layout_storage.addView(fieldView)
            var amount = BigDecimal(0)
            it?.forEach { bean ->
                amount = amount.addEx(bean.storageFee)
                val view = inflater.inflate(R.layout.table_row_storage_fee, table_layout_storage, false)
                view.tv_storage.contentText = bean.storage
                view.tv_unit_price.contentText = bean.unitPrice.toString()
                view.tv_weight.contentText = bean.weight.toString()
                view.tv_storage.contentText = bean.storage
                view.tv_start_date.contentText = bean.startDate.goTimeFormat()
                view.tv_end_date.contentText = bean.endDate.goTimeFormat()
                view.tv_storage_days.contentText = bean.storageDays.toString()
                view.tv_storage_fee.contentText = bean.storageFee.toString()
                view.onSingleLongClicked("编辑", "删除") { s ->
                    if ("编辑" == s) {
                        activityForResult<StorageFeeEditActivity>(
                            Constants.ID to bean.ID,
                            Constants.STORAGE to bean.storage,
                            Constants.START_DATE to bean.startDate,
                            Constants.END_DATE to bean.endDate,
                            Constants.CONTAINER_NO to bean.containerNo,
                            Constants.WEIGHT to bean.weight,
                            Constants.CITY to purchaseProductBean?.shippingInfo?.port
                        ) {
                            storageFee()
                        }

                    } else {
                        messageDialog(msg = "是否删除${bean.storage}?") { _, _ ->
                            httpGet<StorageBean>(UrlConfig.PURCHASE_STORAGE_FEE_DELETE, config = {
                                listParams = listOf("id" to bean.ID)
                            }) {
                                storageFee()
                            }
                        }
                    }
                }
                table_layout_storage.addView(view)
            }
            layout_storage.tv_fee.contentText = "(${amount})"
            tv_storage.contentText = amount.toString()

        }
    }

    /**
     * 清关费用
     */
    private fun clearanceFee() {
        activityForResult<ClearanceFeeEditActivity>(
            Constants.PURCHASE_PRODUCT_ID to purchaseId,
            Constants.DATA to purchaseProductBean?.clearanceFeeList
        ) {
            purchaseProductBean?.clearanceFeeList =
                (it?.getSerializableExtra(Constants.DATA) as? List<ClearanceBean>).orEmpty()
            recycler_view_clearance.visibility =
                if (purchaseProductBean?.clearanceFeeList.isNullOrEmpty()) View.GONE else View.VISIBLE
            clearanceAdapter?.setDataList(purchaseProductBean?.clearanceFeeList.orEmpty())
            purchaseProductBean?.clearanceFeeList?.sumEx { it.value }?.let { amount ->
                tv_clearance_fee.contentText = amount.toString()
                layout_clearance.tv_fee.contentText = "($amount)"
            }
            refreshFee()
        }
    }


    /**
     * 融资费用
     */
    private fun financingFee() {
        httpGet<List<FinancingFeeBean>>(UrlConfig.PURCHASE_FINANCING_FEE_LIST, config = {
            listParams = listOf("purchaseId" to purchaseId)
        }) { financingFeeList ->
            purchaseProductBean?.financingFeeList = financingFeeList
            table_layout_financing.removeAllViews()
            table_layout_financing.visibility = View.GONE
            if (!financingFeeList.isNullOrEmpty()) {
                val view = inflater.inflate(R.layout.table_row_financing_fee_field, table_layout_financing, false)
                table_layout_financing.addView(view)
                table_layout_financing.visibility = View.VISIBLE
            }

            var amount: Double = 0.0
            financingFeeList?.forEach {
                amount += it.financingInterest.orEmpty()
                val view = inflater.inflate(R.layout.table_row_financing_fee, table_layout_financing, false)
                view.find<TextView>(R.id.tv_type).text = it.financingType
                view.find<TextView>(R.id.tv_difference).text = it.financingAmount.toString()
                view.find<TextView>(R.id.tv_day).text = it.financingDays.toString()
                view.find<TextView>(R.id.tv_interest).text = it.financingInterest.toString()
                view.find<TextView>(R.id.tv_rate).text = it.financingRate.toString()
                view.onSingleLongClicked("编辑", "删除") { s ->
                    if (s == "编辑") {
                        activityForResult<FinancingFeeEditActivity>(
                            Constants.DATA to it,
                            Constants.AGENT_ID to purchaseProductBean?.agentId
                        ) {
                            financingFee()
                        }
                    } else if (s == "删除") {
                        httpGet<Any>(UrlConfig.PURCHASE_FINANCING_FEE_DELETE, config = {
                            listParams = listOf("id" to it.ID)
                        }) {
                            refreshFee()
                        }
                    }
                }
                table_layout_financing.addView(view)
            }
            tv_financing_fee.contentText = amount.toString()
            layout_financing.tv_fee.contentText = "(${amount})"
        }
        refreshFee()
    }


    /**
     * 付款单
     */
    private fun settlement() {
        httpGet<List<SettlementFeeBean>>(UrlConfig.PURCHASE_SETTLEMENT_LIST, config = {
            listParams = listOf("purchaseProductId" to purchaseId)
        }) { settlementFeeList ->
            purchaseProductBean?.settlementFeeList = settlementFeeList
            refreshFee()
            if (!settlementFeeList.isNullOrEmpty()) {
                table_layout_settlement.visibility = View.VISIBLE
                settlementFeeList.sumEx { it.amount }.let { totalAmount ->
                    layout_settlement.tv_fee.contentText = "($totalAmount)"
                    tv_settlement_fee.contentText = totalAmount.toString()
                    tv_cost_unit_price.contentText = totalAmount.divEx(productValuationWeight.divEx(10)).toString()
                    tv_sales_unit_price.contentText = purchaseProductBean?.salesPrice.toString()
                    tv_profit.contentText =
                        purchaseProductBean?.salesPrice.mulEx(productValuationWeight.divEx(10)).subEx(totalAmount)
                            .toString()
                }
            } else {
                table_layout_settlement.visibility = View.GONE
            }
            table_layout_settlement.removeAllViews()
            val fieldView = inflater.inflate(R.layout.table_row_settlement, table_layout, false)
            table_layout_settlement.addView(fieldView)
            settlementFeeList?.forEach {
                val view = inflater.inflate(R.layout.table_row_settlement, table_layout_settlement, false)
                view.tv_type.text = it.type
                view.tv_date.text = it.date.goTimeFormat()
                view.tv_amount.text = it.amount.toString()
                view.tv_account.text = it.account
                table_layout_settlement.addView(view)
            }
        }
    }
}